package com.niuwa.p2p.service.impl.credit;

import java.io.StringReader;
import java.rmi.RemoteException;
import java.util.Date;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.niuwa.p2p.dao.credit.ArtificialNationalInfoDao;
import com.niuwa.p2p.dao.credit.CompanyCourtInfoDao;
import com.niuwa.p2p.dao.credit.CorpBaseNationalInfoDao;
import com.niuwa.p2p.dao.credit.NationalPersonShareholderReportDao;
import com.niuwa.p2p.dao.credit.PersonBaseInfoDao;
import com.niuwa.p2p.dao.credit.PersonCheckInfoDao;
import com.niuwa.p2p.dao.credit.PersonCourtInfoDao;
import com.niuwa.p2p.dao.credit.PersonTopManagerInfoDao;
import com.niuwa.p2p.entity.credit.CompanyCheckReqInfo;
import com.niuwa.p2p.entity.credit.CreditInvestigationInfo;
import com.niuwa.p2p.entity.credit.PengYuanRespInfo;
import com.niuwa.p2p.entity.credit.PersonCheckReqInfo;
import com.niuwa.p2p.service.credit.PengYuanCreditService;
import com.niuwa.p2p.service.credit.PyXmlService;
import com.niuwa.p2p.service.pycredit.WebServiceSingleQuery;
import com.niuwa.p2p.service.pycredit.WebServiceSingleQueryProxy;
import com.niuwa.p2p.utils.pycredit.PyDecodeUtils;

/**
 * 
 * @title 鹏元认证服务service
 *
 * @author tennyqin, cupid
 * @version 1.0
 * @created 2015年4月2日
 */
@Service
public class PengYuanCreditServiceImpl implements PengYuanCreditService {

    private static Integer QUERY_ENTERPRISE = 25123; // 企业查询

    @Value("#{propertiesReader['py.userId']}")
    private String userId;

    private static Integer QUERY_POLIC = 25160; // 个人身份证查询
    @Value("#{propertiesReader['py.password']}")
    private String password;

    @Autowired
    private PyXmlService pyXmlervice;
    
    @Autowired
    private ArtificialNationalInfoDao artificialNationalInfoDao;
    @Autowired
    private NationalPersonShareholderReportDao nationalPersonShareholderReportDao;
    @Autowired
    private PersonBaseInfoDao personBaseInfoDao;
    @Autowired
    private PersonCheckInfoDao personCheckInfoDao;
    @Autowired
    private PersonCourtInfoDao personCourtInfoDao;
    @Autowired
    private PersonTopManagerInfoDao personTopManagerInfoDao;
    
    @Autowired
    private CompanyCourtInfoDao companyCourtInfoDao;
    @Autowired
    private CorpBaseNationalInfoDao corpBaseNationalInfoDao;

    private static final String CORP_NAME = "corpName";//用于标识企业返回结果
    
    // 个人查询
    @Override
    public CreditInvestigationInfo getPersonCheckResult(String name, String documentNo) {

        pyXmlervice = new PyXmlServiceImpl();
        userId = "nwjrwsquery";
        password = "{MD5}Nfs6d8ATRVHL8Qc38oRmWw==";

        String queryCondition = "";
        PersonCheckReqInfo personCheckReqInfo = new PersonCheckReqInfo();
        personCheckReqInfo.setQueryType(QUERY_POLIC);
        personCheckReqInfo.setName(name);
        personCheckReqInfo.setDocumentNo(documentNo);
        //21802,
        personCheckReqInfo.setSubreportIDs("10001,10602,96003");
        personCheckReqInfo.setRefID(String.valueOf(new Date().getTime()));
        queryCondition = pyXmlervice.createPersonXml(personCheckReqInfo);
        System.out.println(queryCondition);
        String originalData = queryReport(userId, password, queryCondition);
//        System.out.println("==================================");
//        System.out.println(originalData);
//        System.out.println("==================================");
        PengYuanRespInfo pyri = extractValue(originalData);
        // 返回结果进行解密处理
        String decodeData = PyDecodeUtils.decodePyResp(pyri);
//        System.out.println(decodeData);
//        System.out.println("==================================");
        // 解析xml结果集
        CreditInvestigationInfo creditInvestigationInfo = pyXmlervice.parserPersonXml(decodeData, personCheckReqInfo.getDocumentNo());
        //保存所有数据
        insertCreditInvestigationInfo(creditInvestigationInfo);
        return creditInvestigationInfo;
    }

    // 企业查询
    @Override
    public CreditInvestigationInfo getCompanyByCheckResult(String corpName, String registerNo, String orgCode) {
        pyXmlervice = new PyXmlServiceImpl();
//        userId = "nwjrwsquery";
//        password = "{MD5}Nfs6d8ATRVHL8Qc38oRmWw==";
        String queryCondition = "";
        CompanyCheckReqInfo companyCheckReqInfo = new CompanyCheckReqInfo();
        companyCheckReqInfo.setCorpName(corpName);
        companyCheckReqInfo.setOrgCode(orgCode);
        companyCheckReqInfo.setQueryType(QUERY_ENTERPRISE);
        companyCheckReqInfo.setRegisterNo(registerNo);
        companyCheckReqInfo.setSubreportIDs("95013");
        companyCheckReqInfo.setRefID(String.valueOf(new Date().getTime()));
        
        queryCondition = pyXmlervice.createCompanyXml(companyCheckReqInfo);
        System.out.println(queryCondition);
        String originalData = queryReport(userId, password, queryCondition);
//        System.out.println("==================================");
//        System.out.println(originalData);
//        System.out.println("==================================");
        PengYuanRespInfo pyri = extractValue(originalData);
        // 返回结果进行解密处理
        String decodeData = PyDecodeUtils.decodePyResp(pyri);
//        System.out.println(decodeData);
//        System.out.println("==================================");

        // 解析xml结果集
        CreditInvestigationInfo creditInvestigationInfo = pyXmlervice.parserCompanyXml(decodeData);
        //save all the result
        insertCreditInvestigationInfo(creditInvestigationInfo);
        return creditInvestigationInfo;
    }
    
    // 查询报告
    public String queryReport(String userId, String password, String queryCondition) {
        try {
            WebServiceSingleQuery wsq = new WebServiceSingleQueryProxy();
            return wsq.queryReport(userId, password, queryCondition);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return "";
    }

    // 测试网络
    public String testConnection() {
        String rspStr = "";
        WebServiceSingleQuery wsq = new WebServiceSingleQueryProxy();
        try {
            rspStr = wsq.testConnection();
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return rspStr;
    }

    // 修改用户密码
    public String changePassword(String userId, String oldParrsowd, String newPassword) {
        WebServiceSingleQuery wsq = new WebServiceSingleQueryProxy();
        try {
            return wsq.changePassword(userId, oldParrsowd, newPassword);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return "";
    }

    private PengYuanRespInfo extractValue(String originData) {
        PengYuanRespInfo pyri = new PengYuanRespInfo();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            StringReader sr = new StringReader(originData);
            InputSource is = new InputSource(sr);
            Document doc = builder.parse(is);

            Element rootElement = doc.getDocumentElement();
            NodeList nodes = rootElement.getChildNodes();
            for (int i = 0; i < nodes.getLength(); i++) {
                Node node = nodes.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element child = (Element) node;

                    switch (child.getNodeName()) {
                    case "status":
                        pyri.setStatus(child.getTextContent());
                        break;
                    case "errorCode":
                        pyri.setErrorCode(child.getTextContent());
                        break;
                    case "errorMsg":
                        pyri.setErrorMsg(child.getTextContent());
                        break;
                    case "returnValue":
                        pyri.setEncryptData(child.getTextContent());
                        break;
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return pyri;
    }

    /*
     * 更新鹏元征信数据，将历史数据进行删除处理
     */
    @Override
    public void insertCreditInvestigationInfo(CreditInvestigationInfo cigi) {
        //企业征信结果
        if(cigi.getQueryConditionInfo().getName().equalsIgnoreCase(CORP_NAME)){
            //企业基本信息
            String corpName = cigi.getCorpBaseNationalInfo().getCorpName();
            //删除旧信息，暂时不做删除处理;
//            corpBaseNationalInfoDao.deleteByCorpName(corpName);
//            companyCourtInfoDao.deleteByCorpName(corpName);
            //添加新信息
            corpBaseNationalInfoDao.insert(cigi.getCorpBaseNationalInfo());
            for(int k = 0; k < cigi.getCompanyCourtInfo().size(); k++){
                companyCourtInfoDao.insert(cigi.getCompanyCourtInfo().get(k));
            }
        }else{
            //个人征信结果
            String docNo = cigi.getPersonBaseInfo().getDocNo();
            //删除，暂时不做删除处理;
//            artificialNationalInfoDao.deleteByDocNo(docNo);
//            nationalPersonShareholderReportDao.deleteByDocNo(docNo);
//            personBaseInfoDao.deleteByDocNo(docNo);
//            personCheckInfoDao.deleteByDocNo(docNo);
//            personCourtInfoDao.deleteByDocNo(docNo);
//            personTopManagerInfoDao.deleteByDocNo(docNo);
            
            //增加
            for(int k = 0; k < cigi.getArtificialNationalInfos().size(); k++){
                artificialNationalInfoDao.insert(cigi.getArtificialNationalInfos().get(k));
            }
            for(int k = 0; k < cigi.getNationalPersonShareholderReport().size(); k++){
                nationalPersonShareholderReportDao.insert(cigi.getNationalPersonShareholderReport().get(k));
            }
            personBaseInfoDao.insert(cigi.getPersonBaseInfo());
            personCheckInfoDao.insert(cigi.getPersonCheckInfo());
            for(int k = 0; k < cigi.getPersonCourtInfo().size(); k++){
                personCourtInfoDao.insert(cigi.getPersonCourtInfo().get(k));
            }
            for(int k = 0; k < cigi.getPersonTopManagerInfo().size(); k++){
                personTopManagerInfoDao.insert(cigi.getPersonTopManagerInfo().get(k));
            }
        }
    }
    
    public static void main(String[] args) {
        PengYuanCreditServiceImpl impl = new PengYuanCreditServiceImpl();
        //impl.getPersonCheckResult("吴强", "362525198608220031");
//        String testValue = FileUtil.readTotalFile("d:\\test.xml");
//        PengYuanRespInfo pyir = impl.extractValue(testValue);
//        System.out.println(PyDecodeUtils.decodePyResp(pyir));

        impl.getCompanyByCheckResult("江苏省苏州昆山市亚香日用香料有限公司", "", "");
    }
}
